#include "PlayerHealthComponent.h"
#include "..\Managers\RenderManager.h"
#include "ComponentVisitor.h"

PlayerHealthComponent::PlayerHealthComponent(const vn::Vector2& p_position, int p_minHealth, int p_maxHealth, float p_delay) : HealthComponent(p_minHealth, p_maxHealth, p_delay), m_position(p_position)
{
	m_bar = RenderManager::getSingleton().getRenderEngine()->createSprite(2, "hud_life", 1.5f);
	m_middle = RenderManager::getSingleton().getRenderEngine()->createSprite(2, "hud_middle", 1.0f);
	m_top = RenderManager::getSingleton().getRenderEngine()->createSprite(2, "hud_top", 1.0f);
	m_bot = RenderManager::getSingleton().getRenderEngine()->createSprite(2, "hud_bot_zero", 1.0f);

	m_top->setPosition(p_position);
	vn::IntRect rect = m_middle->getTextureRect();
	m_middle->setTextureRect(rect.x, rect.y, rect.w, rect.h + m_maxHealth);
	rect = m_top->getTextureRect();
	m_middle->setPosition(p_position.x, p_position.y + rect.h);
	m_barStart = static_cast<float>(m_middle->getTextureRect().h + m_top->getTextureRect().h);
	m_bot->setPosition(p_position.x, p_position.y + m_middle->getTextureRect().h + m_top->getTextureRect().h);
	m_bar->setPosition(p_position.x, p_position.y + m_barStart);
	synchronize();
}

PlayerHealthComponent::~PlayerHealthComponent(void)
{
	RenderManager::getSingleton().getRenderEngine()->destroySprite(m_bar);
}

void PlayerHealthComponent::decreaseHealth(int p_value)
{
	HealthComponent::decreaseHealth(p_value);
	synchronize();
}

void PlayerHealthComponent::increaseHealth(int p_value)
{
	HealthComponent::increaseHealth(p_value);
	synchronize();
}

void PlayerHealthComponent::setHealth(int p_value)
{
	HealthComponent::setHealth(p_value);
	synchronize();
}

inline void PlayerHealthComponent::synchronize()
{
	vn::IntRect rect = m_bar->getTextureRect();
	m_bar->setTextureRect(rect.x, rect.y, rect.w, m_health);
	m_bar->setOrigin(m_bar->getOrigin().x, static_cast<float>(m_health));
}

void PlayerHealthComponent::init()
{
	synchronize();
}

void PlayerHealthComponent::update(const GameTime& p_gameTime)
{
	HealthComponent::update(p_gameTime);
}

void PlayerHealthComponent::acceptVisitor(ComponentVisitor* p_componentVisitor)
{
	p_componentVisitor->visitPlayerHealthComponent(this);
}